<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改文章</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>

</head>
<body>
<form class="layui-form" action="" method="POST">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">链接标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" lay-verify="required" autocomplete="off"
                           placeholder="请输入链接标题" class="layui-input" maxlength="100" id="articleTitle">
                    <div id="titleCharCount" class="char-count  ">0/100</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">链接排序</label>
                <div class="layui-input-block">
                    <input type="number" min="0" max="65535" name="sort" placeholder="请输入链接排序"
                           class="layui-input" lay-verify="required" id="channelSort">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">链接路径</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入链接路径" lay-verify="required"
                              class="layui-textarea"
                              autocomplete="off" maxlength="200" id="articleDescription"></textarea>
                    <div id="descCharCount" class="char-count ">0/200</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">发布日期</label>
                <div class="layui-input-block">
                    <input name="articleTime" type="text" lay-verify="required" class="layui-input" autocomplete="off"
                           id="ID-laydate-type-datetime"
                           placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>
            <div class="layui-form-item" id="publishedDelay">
                <label class="layui-form-label">发布方式</label>
                <div class="layui-input-block">
                    <input type="radio" name="way" value="1" title="现在发布" id="now" lay-filter="way-radio-filter"
                           checked>
                    <input type="radio" name="way" value="2" title="定时发布" id="delay" lay-filter="way-radio-filter">
                </div>
            </div>
            <div class="layui-form-item" style="display: none" id="publishedDate">
                <label class="layui-form-label">定时发布日期</label>
                <div class="layui-input-block">
                    <input type="text" name="publishedTime" class="layui-input" autocomplete="off"
                           id="ID-laydate-type-datetime1"
                           placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>
            <div class="layui-form-item" id="isPushed">
                <label class="layui-form-label">是否推送</label>
                <div class="layui-input-block">
                    <input type="radio" name="pw" value="1" title="否" id="pf" lay-filter="pw-radio-filter">
                    <input type="radio" name="pw" value="2" title="是" id="pt" lay-filter="pw-radio-filter">
                </div>
            </div>
            <div class="layui-form-item" style="display: none" id="selectChannel">
                <label class="layui-form-label">选择栏目</label>
                <div class="layui-input-block">
                    <input type="text" id="parent-tree-input" placeholder="请选择栏目" class="layui-input"
                           readonly="readonly">
                    <!-- 清空按钮 -->
                    <button type="button" id="clear-parent" class="layui-btn  layui-btn-sm"
                            style="position: absolute; right: 5px; top: 5px;">
                        清空
                    </button>
                    <!-- 用于提交的隐藏字段 -->
                    <div id="parent-tree"
                         style="display:none; position: absolute; z-index: 1000; background-color: #fff; border: 1px solid #d2d2d2; width: 50%"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn  layui-btn-sm" lay-submit="" lay-filter="article-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>

<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'jquery', 'upload', 'element', 'laydate', 'tree'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let element = layui.element;
        let laydate = layui.laydate;
        let tree = layui.tree;
        let baseURL = /*[[@{/}]]*/ '';


        // 使用 jQuery 来监听标题输入框的输入事件
        $('#articleTitle').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#titleCharCount').text(currentLength + "/" + maxLength);
        });

        // 使用 jQuery 来监听描述输入框的输入事件
        $('#articleDescription').on('input', function () {
            let maxLength = $(this).attr('maxlength');
            let currentLength = $(this).val().length;
            $('#descCharCount').text(currentLength + "/" + maxLength);
        });

        laydate.render({
            elem: '#ID-laydate-type-datetime',
            type: 'datetime',
            fullPanel: true,
        });
        laydate.render({
            elem: '#ID-laydate-type-datetime1',
            type: 'datetime',
            fullPanel: true,
        });
        form.on('radio(way-radio-filter)', function (data) {
            if (Number(data.elem.value) === 2) {
                $('#publishedDate').show();
            } else {
                $('#publishedDate').hide();
            }
        });
        if (parent.publishedTime !== "" && parent.publishedTime !== null) {
            $('#delay').prop('checked', true)
            $('#publishedDate').show();
            $('input[name=publishedTime]').val(parent.publishedTime);
            form.render('radio');
        } else {
            $('#now').prop('checked', true)
            form.render('radio');
        }


        let channelTitles = parent.channelNames
        let channelIds = parent.channelIds
        form.on('radio(pw-radio-filter)', function (data) {
            if (Number(data.elem.value) === 2) {
                $('#selectChannel').show();
                channelTitles = parent.channelNames
                channelIds = parent.channelIds
                $('#parent-tree-input').val(channelTitles);
            } else {
                $('#selectChannel').hide();
                channelTitles = ""
                channelIds = []
            }
        });


        // 初始化树形结构的隐藏状态
        $('#parent-tree').hide();

        // 点击输入框时显示树形结构
        $('#parent-tree-input').on('click', function () {
            $('#parent-tree').toggle(); // 显示或隐藏树形结构
        });

        // 渲染父级栏目树形结构


        if (channelIds.length > 1) {
            $('#parent-tree-input').val(channelTitles); // 填充栏目名称
            $('#pt').prop('checked', true)
            form.render('radio')
            $('#selectChannel').show();
        } else {
            $('#pf').prop('checked', true)
            form.render('radio')
            $('#selectChannel').hide();
        }
        $.get(baseURL + "cms/channel/getParentMenus", function (data) {
            let d;
            if (data != null) {
                d = filterByChannelId(data, parent.channelId)
                d = findNodesWithCodeList(d)
            }
            tree.render({
                elem: '#parent-tree', // 树形组件容器
                data: d, // 后端返回的树形数据
                click: function (obj) {
                    if (obj && obj.data) {
                        if (channelTitles.includes(obj.data.title)) {
                            return;
                        }
                        let s = "";
                        if (channelTitles === "") {
                            s = "";
                        } else {
                            s = ",";
                        }
                        channelTitles += s + obj.data.title
                        channelIds.push(obj.data.id)
                        $('#parent-tree-input').val(channelTitles); // 填充栏目名称
                        // $('#parent-tree').hide(); // 隐藏树形选择框
                    } else {
                        console.error("无法获取节点数据");
                    }
                }
            });
        });

        // 点击清空按钮时，清空输入框和隐藏树形结构
        $('#clear-parent').on('click', function () {
            $('#parent-tree-input').val(''); // 清空输入框
            channelIds = []
            channelTitles = ""
            $('#parent-tree').hide(); // 隐藏树形结构
        });
        // 点击空白区域时，关闭树形选择框
        $(document).on('click', function (e) {
            if (!$(e.target).closest('#parent-tree-input').length && !$(e.target).closest('#parent-tree').length) {
                $('#parent-tree').hide();
            }
        });

        // 树组件过滤函数
        function filterByChannelId(data, channelId) {
            return data.filter(item => {
                if (item.id == channelId) {
                    return false;
                }
                if (item.children && item.children.length > 0) {
                    item.children = filterByChannelId(item.children, channelId);
                    return true;
                }
                return true;
            });
        }


        function findNodesWithCodeList(data) {
            let result = []; // 用于存储符合条件的节点

            function recursiveSearch(nodes) {
                if (!nodes || nodes.length === 0) return;

                for (let node of nodes) {
                    if (node.code === "LINK") {
                        result.push(node); // 如果当前节点的 code 是 "LIST"，加入结果数组
                    }
                    if (node.children && node.children.length > 0) {
                        recursiveSearch(node.children); // 递归查找子节点
                    }
                }
            }

            recursiveSearch(data); // 从根节点开始递归查找
            return result; // 返回结果数组
        }


        // 表单提交
        form.on('submit(article-save)', function (data) {
            let way = data.field.way
            let publishedTime = data.field.publishedTime
            if (Number(way) === 2) {
                if (!publishedTime) {
                    layer.msg("请填写发布日期！", {icon: 2, time: 1500});
                    return false;
                } else {
                    const time = new Date(publishedTime);
                    const currentTime = new Date();
                    currentTime.setMinutes(currentTime.getMinutes() + 1);
                    if (time <= currentTime) {
                        layer.msg("定时发布时间必须大于当前时间一分钟！", {icon: 2, time: 1500});
                        return false;
                    }
                }
            } else {
                data.field.publishedTime = null
            }
            data.field.channelId = parent.channelId
            data.field.articleId = parent.articleId
            data.field.status = parent.state
            data.field.content = ""
            channelIds.push(parent.channelId)
            data.field.channelIds = channelIds
            let loading = layer.msg('正在提交中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            });
            $.ajax({
                url: baseURL + 'cms/infoArticle/update',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            parent.layui.table.reload("article-table");
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false;
        });
    });
</script>
</body>
</html>

